<script>
  /* eslint-disable */
  import '@/common/stat';
  import {
    SITE_PAY,
    STORGE_GET_USER_TIME
  } from '@/common/const';
  import Vue from 'vue';

  const themeListeners = [];
  // 不需要检验付费的页面，避免付费模式直接跳到付费页面
  const pageItem = [
    'pages/site/partner-invite',
    'pages/user/login',
    'pages/user/register',
    'pages/user/phone-login-register',
  ];
  // #ifdef APP-PLUS
  import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
  // #endif
  export default {
    data() {
      return {
        statisticsCode: '', // 统计代码
      };
    },
    globalData: {
      // #ifdef H5
      appLoadedStatus: false,
      // #endif
      themeChanged(theme) {
        Vue.prototype.$u.currentTheme = theme;
        themeListeners.forEach(listener => {
          listener(theme);
        });
        uni.setStorage({
          key: 'theme',
          data: theme,
        });
      },
      watchThemeChange(listener) {
        if (themeListeners.indexOf(listener) < 0) {
          themeListeners.push(listener);
        }
      },
      unWatchThemeChange(listener) {
        const index = themeListeners.indexOf(listener);
        if (index > -1) {
          themeListeners.splice(index, 1);
        }
      },
    },
    async onLaunch(e) {
      // #ifdef APP-PLUS
      checkUpdate();
      // #endif

      const init = async () => {
         const forums = await this.$store.dispatch('jv/get', [
          'forum',
          {
            params: {
              include: 'users',
            },
          },
        ]);
      
         // forums 初始化完成 触发事件
        uni.$emit('inited', forums);
         const userId = this.$store.getters['session/get']('userId');
        let user = {};
        if (userId) {
          const params = {
            pid:userId,
            include: 'groups,wechat',
          };
          user = await this.$store.dispatch('jv/get', [`user`, {
            params
          }]);
          uni.setStorageSync(STORGE_GET_USER_TIME, new Date().getTime());
        }

        this.statisticsCode = forums.setSite.siteStat;
        uni.$emit('stat', {
          statisticsCode: this.statisticsCode,
        });
        let currentPage = {};

        const pages = getCurrentPages();
        if (pages.length > 0) {
          currentPage = pages[pages.length - 1];
        }
        if (forums.setReg) {
          uni.setStorageSync('register_type', forums.setReg.registerType);
        }

        if (forums.setSite.siteMode === SITE_PAY) {
          // #ifndef H5
          const res = uni.getSystemInfoSync();
          if (res.platform === 'ios') {
            this.$store.dispatch('forum/setError', {
              loading: false,
              code: 'dataerro'
            });
            return;
          }
          // #endif
          if (pages.length > 0) {
            currentPage = pages[pages.length - 1];
            if (currentPage.route === 'pages/user/pc-login') {
              uni.redirectTo({
                url: currentPage.__page__.fullPath,
              });
              return;
            }
            if (currentPage.route === 'pages/user/pc-relation') {
              uni.redirectTo({
                url: currentPage.__page__.fullPath,
              });
              return;
            }
            if (
              !user.paid &&
              currentPage.route !== 'pages/site/info' &&
              pageItem.indexOf(currentPage.route) === -1
            ) {
              uni.redirectTo({
                url: '/pages/site/info',
              });
            }
            // 站点付费
          } else if (!user.paid) {
            // 在这里会导致一个问题，当进入user/wechat中的时候，会因为这里先执行了跳转，导致进入了user/wechat后，因为这里产生了跳转，导致user/wechat无法正常执行onload，导致无法验证用户的登录状态。
            if (uni.getStorageSync('oauth_wechat') !== 1 && uni.getStorageSync('h5_wechat_login') !== 1) {
              uni.redirectTo({
                url: '/pages/site/info',
              });
            }
          }
        }

        // #ifdef H5
        this.globalData.appLoadedStatus = true;
        uni.$emit('apploaded');
        // #endif
        if (!this.$store.state.forum.error.code) {
          this.$store.dispatch('forum/setError', {
            loading: false
          });
        }
      };

      try {
         await init();

      } catch (errs) {
        console.log('errs',errs)
        if (errs && errs.data && errs.data.errors) {
          if (errs.data.errors[0].code === 'access_denied') {
            this.$store.dispatch('session/logout').then(init);
          } else {
            this.$store.dispatch('forum/setError', {
              loading: false,
              ...errs.data.errors[0],
            });
          }
        }
      }
     let forums= this.$store.getters['jv/get']('forum/1')
      console.log('forums',forums)
    },

    onShow(options) {

      // 解决各类回调的兼容问题,验证码捕获captchaResult
      // #ifdef MP-WEIXIN
      if (!this.captchaTicketExpire) this.captchaTicketExpire = {};
      if (options.scene === 1038 && options.referrerInfo.appId === 'wx5a3a7366fd07e119') {
        const result = options.referrerInfo.extraData;
        if (result && result.ret === 0) {
          const theTicket = result.ticket;
          if (!this.captchaTicketExpire[theTicket]) {
            this.captchaTicketExpire[theTicket] = true;
            this.$u.event.$emit('captchaResult', result);
          }
        } else {
          this.$u.event.$emit('closeChaReault', result);
          // 用户关闭了验证码
        }
      }
      // #endif
      //商城
      //#ifdef APP-PLUS

      getApp({
        allowDefault: true
      }).globalData.vueObj = this;
      //#endif

    },
    onHide() {},
    onPageNotFound(e) {

      let url = '/pages/common/error';
      if (/^\/thread\/\d+$/i.test(e.path)) {
        const matchs = e.path.match(/^\/thread\/(\d+)$/i);
        url = `/topic/index?id=${matchs[1]}`;
      } else if (/^\/user\/\d+$/i.test(e.path)) {
        const matchs = e.path.match(/^\/user\/(\d+)$/i);
        url = `/pages/profile/index?userId=${matchs[1]}`;
      } else if (e.path === '/site/partner-invite' && e.query.code) {
        url = `/pages/site/partner-invite?code=${e.query.code}`;
      } else if (/^\/category\/\d+$/i.test(e.path)) {
        const matchs = e.path.match(/^\/category\/(\d+)$/i);
        url = `/?categoryId=${matchs[1]}`;
      } else if (/^\/topic\/\d+$/i.test(e.path)) {
        const matchs = e.path.match(/^\/topic\/(\d+)$/i);
        url = `/topic/content?id=${matchs[1]}`;
      }

      uni.redirectTo({
        url
      });
    },
    methods: {

      // 商城
      /**
       * 小程序启动场景
       */
      async onStartupScene(query) {
        // 获取场景值
        let scene = utils.getSceneData(query);
        // 记录推荐人id
        let refereeId = query.referee_id;
        if (refereeId > 0) {
          if (!uni.getStorageSync('referee_id')) {
            uni.setStorageSync('referee_id', refereeId);
          }
        }
        // 记录分销人id
        let uid = scene.uid;
        if (uid > 0) {
          if (!uni.getStorageSync('referee_id')) {
            uni.setStorageSync('referee_id', uid);
          }
        }
        // 如果是h5，设置app_id
        // #ifdef  H5
        let appId = query.app_id;
        if (appId > 0) {
          this.config.app_id = appId;
        }
        // #endif
      },
      getTabBarLinks() {
        uni.request({
          url: this.config.app_url + '/index.php/api/index/nav',
          data: {
            app_id: this.config.app_id
          },
          success: (result) => {
            let vars = result.data.data.vars;
            uni.setTabBarStyle({
              color: vars.no_color,
              selectedColor: vars.color,
            })
            vars.menus.forEach((item, index) => {
              if (index == 5) {
                return;
              }
              uni.setTabBarItem({
                index: index,
                text: item.text,
                iconPath: item.iconPath,
                selectedIconPath: item.selectedIconPath
              });
            });
            // #ifdef  MP-WEIXIN
            if (vars.menu_type == 2) {
              let tabbar = vars.menus[5];
              uni.setTabBarItem({
                index: 2,
                text: tabbar.text,
                iconPath: tabbar.iconPath,
                selectedIconPath: tabbar.selectedIconPath
              })
            }
            uni.setStorageSync('middle', vars.menu_type);
            // #endif
            // #ifndef  MP-WEIXIN
            uni.setStorageSync('middle', 1);
            // #endif
          }
        });
      }
    }
  };
</script>

<style lang="scss">
  /* 每个页面公共css */
  @import '@/styles/base/reset.scss';
  // @import  './components/qui-icon/style.scss';
  /*每个页面公共css */

</style>
